<template>
	<view v-show="isShow">
		<u-form-item label="下一环节：">
			<u-radio-group v-model="nextTaskDefKey">
				<u-radio 
					v-for="opt in nextTaskInfoList" 
					:key="opt.taskDefKey" 
					:name="opt.taskDefKey" 
					@change="handleNextTaskNodeChange(opt.taskDefKey)" >
					{{ opt.taskDefName }}
				</u-radio>
			</u-radio-group>
		</u-form-item>
		<u-form-item label="办理人：" v-if="needSelectNextUsers" prop="userList" :wrap="true">
			<!-- <u-tag  
				v-for="(item, index) in nextTaskDefKeyRelNextUsers" 
				:key="index" 
				:text="item.name" 
				:closeable="uTagProps.closeable"  
				:size="uTagProps.size" 
				:shape="uTagProps.shape" 
				@close="handleCloseNextUser(item)">
			</u-tag> -->
		    <u-checkbox-group :wrap="radioCheckWrap" :width="radioCheckWidth">
			  <u-checkbox v-model="item.checked" v-for="(item, index) in nextTaskDefKeyRelNextUsers" :key="index" :name="item.name">{{ item.name }}</u-checkbox>
		    </u-checkbox-group>
			<u-icon v-if="enableSelNextUser" name="plus-circle-fill" size="50" color="#3d87ff" style="margin-left: 10rpx;" @click="onSelectNextUsers"></u-icon>
		</u-form-item>
		<js-choose-user-popup
			ref="chooseUser" 
			v-if="userDialog.isVisible" 
			@submit="fillUserAndClose" 
			@close="closeChooseUser" 
			:mode="userDialog.mode" 
			:show-clear-btn-prop="false" 
			:show-close-btn-prop="true" 
			:multiple="userDialog.multiple"
			:action="userDialog.chooseUserUrl"
			:default-selected-user-list="(nextTaskInfoList.length ===0 || nextTaskInfoList[0].nextUsers === '') ? [] : nextTaskInfoList[0].nextUsers"
		></js-choose-user-popup>
	</view>
</template>

<script>
import DATATYPE_MAP from '@/pages/flowableplus/work/enums/DataTypeEnum.js';

export default {
	components: {},
	props: {
		// 流程定义ID
		procDefId: {
			type: String,
			default: ''
		},
		// 任务节点定义Key
		taskDefKey: {
			type: String,
			default: ''
		},
		// 流程定义Key
		procDefKey: {
			type: String,
			default: ''
		},
		// 表单数据对象
		formData: {
			type: Object,
			default: () => {}
		},
		flowData: {
			type: Object,
			default: () => {}
		},
		isShowProp: {
			type: Boolean,
			default: true
		},
		enableSelNextUserProp: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			size: 'small',
			// 当前用户任务定义key
			nextTaskDefKey: '',
			// 为了指定下一级审批人，下一用户任务节点信息对象集合，其中对象属性有 {taskDefKey,taskDefName,dataSourceUrl,nextUsers}
			nextTaskInfoList: [],
			allNextTaskInfoList: [],
			isExistCandidateusersApiGetConf: true,
			userList: [],
			isShow: this.isShowProp,
			needSelectNextUsers: true,
			radioCheckWidth:'auto',
			radioCheckWrap: false,
			userDialog: {
				title: '人员选择',
				isVisible: false,
				selectable: true,
				multiple: true,
				deptType: '1',
				deptId: '',
				showClose: true,
				displayChooseUser: true,
				mode: 'bottom',
				chooseUserUrl: ''
			},
			uTagProps: {
				closeable: true,
				size: 'default',
				shape: 'square',
			},
			enableSelNextUser: this.enableSelNextUserProp,
		};
	},
	computed: {
		nextTaskDefKeyRelNextUsers() {
			let nextUsers = [];
			let nextUserTaskInfo = this.nextTaskInfoList.find((elem) => elem.taskDefKey === this.nextTaskDefKey);
			if (nextUserTaskInfo && nextUserTaskInfo.nextUsers) {
				nextUsers = nextUserTaskInfo.nextUsers;
			}
			return nextUsers;
		}
	},
	watch: {
		nextTaskDefKey: function (val) {
			this.resolveNextUsers(val);
			let nextUserTaskInfo = this.nextTaskInfoList.find((elem) => elem.taskDefKey === this.nextTaskDefKey);
			if (nextUserTaskInfo) {
				this.needSelectNextUsers = nextUserTaskInfo.selectUserDisplay;
			}
		}
	},
	created() {
		// 初始选择用户URL
		this.userDialog.chooseUserUrl = `/api/blade-system/user/user-list-by-dept-type?deptId=${this.vuex_deptId}`;
		this.initNextUserNode();
	},
	methods: {
		/**
		 * 获取指定的任务节点（taskDefKey）的下一个用户任务节点
		 */
		initNextUserNode() {
			// procDefId 如：Process_1706878207549:12:d3ddc684-c3f3-11ee-92c3-1c1bb5458fc2  流程标识:版本号:部署ID
			// procDefKey 如：Process_1706878207549
			// nextFlowNode接口，当前使用的是procDefId来查询下一级用户节点。procDefId已经固定了版本号，所以流程模型定义修改了，当前procDefId对应的流程模型XML内容还是旧的版本。
			// procDefKey 流程标识，一个流程标识下会有多个版本
			let procDefId = this.procDefId;
			let taskDefKey = this.taskDefKey;
			let procDefKey = this.procDefKey;
			let params = {
				procDefId,
				procDefKey,
				taskDefKey
			};
			this.$u.get(this.vuex_config.adminPath + '/api/blade-flowable-plus/workflow/task/nextFlowNodeByTaskVO', params).then((res) => {
				let data = res.data;
				if (data && data.length > 0) {
					// console.info(data);
					data.forEach((node, index) => {
						// 任务节点定义ID
						let taskDefKey = node.id;
						// 任务节点名称
						let taskDefName = node.name;
						// 候选用户el表达式
						let candidateUsersExpression = '';
						if (node.candidateUsers && node.candidateUsers.length > 0) {
							candidateUsersExpression = node.candidateUsers[0];
						}
						// 候选用户的数据源请求地址
						let dataSourceUrl = '';
						let attributes = node.attributes;
						let nextUsers = [];
						let selectUserDisplay = false;
						//结束节点
						if (node.assignee === undefined) {
							let taskDefNode = {
								taskDefKey,
								taskDefName,
								nextUsers,
								selectUserDisplay
							};
							this.nextTaskInfoList.push(taskDefNode);
						} else if (attributes && attributes.dataType && attributes.dataType.length > 0 && attributes.text && attributes.text.length > 0) {
							let value = attributes.dataType[0].value;
							let text = attributes.text[0].value;
							if (value === DATATYPE_MAP.CANDIDATEUSERS_API_GET && text) {
								dataSourceUrl = text;
							}
							if (node.assignee !== '${initiator}') {
								selectUserDisplay = true;
							}
							let taskDefNode = {
								taskDefKey,
								taskDefName,
								candidateUsersExpression,
								dataSourceUrl,
								nextUsers,
								selectUserDisplay
							};
							this.nextTaskInfoList.push(taskDefNode);
						}
					});
					this.allNextTaskInfoList=this.nextTaskInfoList;
				}
				if (this.nextTaskInfoList.length > 0) {
					this.nextTaskDefKey = this.nextTaskInfoList[0].taskDefKey;
				} else {
					this.isExistCandidateusersApiGetConf = false;
					// 没有下一环节的信息数据，则组件内容不展示
					this.isShow = false;
				}
				// 执行回调函数
				// if (callBack && typeof callBack === 'function') {
				//   callBack();
				// }
			});
		},
		onSelectNextUsers() {
			// console.log('onSelectNextUsers', this);
			this.userDialog.isVisible=true;
			this.$nextTick(() => {
				this.$refs.chooseUser.open();
			})
		},
		/**
		 * 解析并设置nextUsers的值
		 */
		resolveNextUsers(val) {
			let vm = this;
			// 1. 解析所有的占位符变量数组，eg: ['${intervieweePhone}','${currentUserDeptId}'],${}里面的内容对应的是页面表单的变量
			let placeholderVars = [];
			let selectedNextTask = this.nextTaskInfoList.filter((item) => item.taskDefKey === val)[0];
			let { taskDefKey, taskDefName, dataSourceUrl } = selectedNextTask;
			if (dataSourceUrl) {
				// 解析？后面的参数
				let paramsStr = dataSourceUrl.substring(dataSourceUrl.indexOf('?') + 1);
				if (paramsStr) {
					let paramArr = paramsStr.split('&');
					if (paramArr && paramArr.length > 0) {
						paramArr.forEach((param) => {
							let paramContent = param.split('=');
							if (paramContent && paramContent.length === 2 && paramContent[1].indexOf('$') !== -1) {
								placeholderVars.push(paramContent[1]);
							}
						});
					}
				}
				// 2. 查找占位符变量对应的表单属性与属性值
				let placeholderVarRealValueObj = {};
				placeholderVars.forEach((pvar) => {
					let formPropKey = pvar.replace('${', '').replace('}', '');
					if (this.formData[formPropKey]) {
						// 有实际值放到placeholderVarRealValueObj中
						placeholderVarRealValueObj[pvar] = this.formData[formPropKey];
					}
					if (this.flowData.curTask[formPropKey]) {
						// 有实际值放到placeholderVarRealValueObj中
						placeholderVarRealValueObj[pvar] = this.flowData.curTask[formPropKey];
					}
					if (this.flowData.currentUser[formPropKey]) {
						// 有实际值放到placeholderVarRealValueObj中
						placeholderVarRealValueObj[pvar] = this.flowData.currentUser[formPropKey];
					}
					if (formPropKey === 'nextTaskDefKey') {
						placeholderVarRealValueObj[pvar] = this.nextTaskDefKey;
					}
				});
				// 3. 发起请求调用获取下一环节审批人接口
				let sendArr = [];
				for (let key in placeholderVarRealValueObj) {
					if (placeholderVarRealValueObj.hasOwnProperty(key)) {
						dataSourceUrl = dataSourceUrl.replace(key, placeholderVarRealValueObj[key]);
					}
				}
				// console.log('解析后的dataSourceUrl', dataSourceUrl);
				//如果dataSourceUrl中还有${}占位变量没有解析，则不进行请求加载
				if (dataSourceUrl && dataSourceUrl.indexOf('${') === -1) {
					let apiUrl = this.vuex_config.adminPath + dataSourceUrl;
					sendArr.push(apiUrl);
				}
				Promise.all(sendArr.map((sendEndpoint) => this.$u.get(this.vuex_config.adminPath + sendEndpoint))).then(results => {
				  // console.log("results",results);
				  // results 是数组
				  if (results && results.length > 0) {
				    results.forEach((result, index) => {
				      // console.log("result", result, "index", index);
				      let nextUserTaskInfo = this.nextTaskInfoList[index];
				      nextUserTaskInfo['nextUsers'] = result.data || [];
				    })
				    // 4. 默认第一个下一级任务节点
				    if (this.nextTaskInfoList.length > 0) {
				      this.nextTaskDefKey = this.nextTaskInfoList[0].taskDefKey;
				    }
				    // 5. 执行回调函数
				    // if (callBack && typeof callBack === 'function') {
				    //   callBack();
				    // }
				  }
				});
			}
		},
		handleNextTaskNodeChange(val) {
			// console.log('val', val);
		},
		handleCloseNextUser(item) {
			if(this.nextTaskDefKeyRelNextUsers.length === 1) {
				this.$u.toast('办理人不能为空！');
				return;
			}
			this.nextTaskDefKeyRelNextUsers.splice(this.nextTaskDefKeyRelNextUsers.indexOf(item), 1);
		},
		checkIsSetApprover() {
			if (this.needSelectNextUsers) {
				let selectedNextTaskList = this.nextTaskInfoList.filter((item) => item.taskDefKey === this.nextTaskDefKey);
				let isSetApprover = true;
				selectedNextTaskList.forEach((item, index) => {
				  if(item.nextUsers.length<=0){
					isSetApprover = false;
					return isSetApprover;
				  }else{
					let checkedCnt=item.nextUsers.filter(it=> it.checked===true);
					if(checkedCnt.length<=0){
					  isSetApprover = false;
					  return isSetApprover;
					}
				  }
				})
				return isSetApprover;
			} else {
				return true;
			}
		},
		getNextUserTaskInfoArr() {
			let data=this.nextTaskInfoList.filter(item=> item.taskDefKey===this.nextTaskDefKey);
			const copyData = JSON.parse(JSON.stringify(data));
			copyData.forEach((item, index) => {          
				let checkedUsers=item.nextUsers.filter(it=> it.checked===true);
				item.nextUsers=checkedUsers;
			})
			return copyData;
		},
		selectedClosed() {
			this.userDialog.isVisible = false;
		},
		fillUserAndClose() {
			this.userDialog.isVisible = false;
			let selectUser = this.$refs.chooseUser.getData();
			if (selectUser.length > 0) {
				let selectUserList = [];
				selectUser.some(function (item) {
					selectUserList.push({ id: item.id, name: item.name, userId: item.id });
				});
				let nextUserTaskInfo = this.nextTaskInfoList.find((elem) => elem.taskDefKey === this.nextTaskDefKey);
				nextUserTaskInfo.nextUsers = selectUserList;
			} else {
				this.userList = [];
			}
			this.$refs.chooseUser.close();
		},
		closeChooseUser() {
			this.userDialog.isVisible = false;
		},
	}
};
</script>

<style lang="scss" scoped>
	.u-tag + .u-tag {
		margin-left: 10rpx;
	}

	.button-new-tag {
		margin-left: 10rpx;
	}
</style>
ss
